﻿@model RightControl.Model.ProductDetail
@using System.Collections.Generic;
@using RightControl.Model;
@{

    ViewBag.Title = "商品详情";
    Layout = "~/Areas/Admin/Views/Shared/_LayoutForm.cshtml";
}

<div class="layui-fluid" style="min-height: 50px; height: 1200px;">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-body" pad15="">
                    <form class="layui-form" id="form">
                        @Html.HiddenFor(x => x.ImageUrl)
                        @Html.HiddenFor(x => x.CreateOn)
                        <blockquote class="layui-elem-quote p10">
                            <div class="layui-form-item">
                                <label class="layui-form-label">对标产品:</label>
                                <div class="layui-input-block">
                                    <input id="inputOriProductUrl" value="@Model.OriProductUrl" lay-verify="required" lay-vertype="tips" class="layui-input" style="width:92%;display:inline" type="text">
                                    <a class="layui-btn layui-btn-xs layui-btn-normal" href="@Model.OriProductUrl" target="_blank"><i class="layui-icon iconfont icon-chakan"></i>访问</a>
                                </div>
                            </div>
                        </blockquote>

                        <blockquote class="layui-elem-quote p10">
                            <div class="layui-form-item">
                                <label class="layui-form-label"><span class="fRed">*</span>主SKU:</label>
                                <div class="layui-input-inline" style="width:15%">
                                    <input id="inputSkuId" value="@Model.SkuId" lay-verify="required" lay-vertype="tips" class="layui-input" type="text">
                                </div>

                                <label class="layui-form-label">价格:</label>
                                <div class="layui-input-inline" style="width:8%">
                                    <input id="inputPrice" value="@Model.Price" lay-verify="required" lay-vertype="tips" class="layui-input" type="text">
                                </div>

                                <label class="layui-form-label">产品类目：</label>
                                <div class="layui-input-inline" style="width:10%">
                                    @Html.CategoryHtml(ViewData["BaseCategory"], @Model.CategoryCode)
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">产品标题:</label>
                                <div class="layui-input-block">
                                    <input id="inputTitle" value="@Model.Title" lay-verify="required" lay-vertype="tips" class="layui-input" type="text">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">产品描述:</label>
                                <div class="layui-input-block" id="divDescription">
                                    @*@Html.TextAreaFor(x => x.Description, new Dictionary<string, object> { { "class", "layui-textarea" }, { "lay-verify", "pass" }, { "lay-vertype", "tips" } })*@
                                </div>
                            </div>
                        </blockquote>

                        <blockquote class="layui-elem-quote p10">
                            <div class="layui-form-item">
                                <label class="layui-form-label">产品图片:</label>
                                <div class="layui-input-block">
                                    @{
                                        List<ProductImage> images = ViewData["productImags"] as List<ProductImage>;
                                        if (images != null) {
                                            for (int i = 0; i < images.Count; i++) {
                                                if (images[i].ImgType == 1) {
                                                    <img style="width:200px;height:200px" src="@images[i].ImgUrl" />
                                                }
                                            }
                                        }
                                    }
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">更新时间:</label>
                                <div class="layui-input-inline">
                                    <input name="ClassName" lay-vertype="tips" class="layui-input" type="text" value="@Model.UpdateOn">
                                </div>
                            </div>
                        </blockquote>

                        <blockquote class="layui-elem-quote p10">
                            <div class="layui-field-box" style="padding:0">
                                <table id="subProductTb" lay-filter="defaultruv"></table>
                                <script type="text/html" id="bar">
                                    @Html.ToolBarHtml(ViewData["ActionList"])
                                </script>
                            </div>
                        </blockquote>

                        <div class="layui-form-item" id="editor" contenteditable="true" style="height:380px;">
                            <input type="hidden" id="hidImage" value="@Model.ImageUrl" />
                            @{
                                if (images != null) {
                                    for (int i = 0; i < images.Count; i++) {
                                        if (images[i].ImgType == 2) {
                                            <img src="@images[i].ImgUrl" />
                                        }
                                    }
                                }
                            }
                            <input type="hidden" id="hidEditorContent" name="editContent" />
                        </div>

                    </form>

                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <a class="layui-btn" lay-submit="Product/updateProduct" lay-filter="submitForm" id="submitForm">立即提交</a>
                            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


 <script src="https://unpkg.com/wangeditor@3.1.1/release/wangEditor.min.js" type="text/javascript"></script>

<script type="text/javascript">
    var despObj = {};
    var E = window.wangEditor
    var editor = new E('#editor');
    function initEditor(selector) {
        editor.customConfig.onchange = function (html) {
            this.editContent = html//动态获取富文本编辑器的内容
            selector("#hidEditorContent").value = html;
        }

        //editor.customConfig.uploadImgShowBase64 = true;
        editor.customConfig.uploadImgServer = "/DataSrv/Product/UploadFiles"; //上传URL
        editor.customConfig.uploadFileName = 'imgFile';
        editor.create()
    }

    function initProperties() {
        if (despObj != null) {
            var count = 0; var rows = '';
            var totalKeys = Object.keys(despObj).length;
            var propTable = '<table cellspacing="0" cellpadding="0" border="0" class="layui-table"><tbody>';
            for (var key in despObj) {
                if (count % 4 == 0) {
                    if (count > 0) rows += '</tr>';
                    rows += '<tr data-index="0"><td style="color:blue;width:5%;" align="right">' + key + '</td><td data-field="' + count + '"style="width:8%"><input type="text" id="prop_' + count + '"class="layui-input" autocomplete="off" value="' + despObj[key] + '"/></td>';
                } else {
                    rows += '<td style="color:blue;width:5%" align="right">' + key + '</td><td data-field="' + count + '"style="width:8%"><input type="text"  id="prop_' + count + '"class="layui-input" autocomplete="off" value="' + despObj[key] + '"/></td>';
                    if (count == totalKeys - 1) rows += '</tr>';
                }
                count++;
            }
            propTable += rows + '</tbody></table>';
            return propTable;
        }
    }

    layui.use(['form'], function () {
        var form = layui.form;
        var $ = layui.$;
        submitForm(form, "编辑成功"); //监听提交
        $("#sltIcon").on("click", function () {
            openSetIcon();
        });

        $("#Position").val('@Model.Title')

        $("#submitForm").on("click", function () {
            var count = 0;
            for (var key in despObj) {
                despObj[key] = $("#prop_" + count).val();
                count++;
            }
            //提交前校验

            var formData = {};
            formData.Id = @Model.Id;
            formData.Title = $("#inputTitle").val();
            formData.SkuId = $("#inputSkuId").val();
            formData.Price = $("#inputPrice").val();
            formData.OriProductUrl = $("#inputOriProductUrl").val();
            formData.CategoryCode = $("#selCategoryCode").val();
            formData.ImageUrl = $("#hidImage").val();
            formData.CreateOn = $("#CreateOn").val();
            formData.Description = JSON.stringify(despObj);
            $.ajax({
                url: "/Datasrv/Product/updateProduct",
                type: "POST",
                data: formData,
                dataType: "json",
                success: function (data) {
                    if (data.state == "success") {
                        common.msgSuccess("更新成功");
                    } else {
                        common.msgError("更新失败");
                    }
                }
            });

            var subProductList = [];
            var subProductRows =  $(".layui-table-main table tbody tr");
            if (subProductRows!=null) {
                for (var i = 0; i < subProductRows.length; i++) {
                    var inputs = $(subProductRows[i]).find('td input');
                    subProductList.push({
                        ProductId:@Model.Id,
                        Color:inputs[1].value,
                        Size:inputs[2].value,
                        SkuId:inputs[3].value,
                        ImageUrl:$(subProductRows[i]).find('td img').attr('src')});
                }
                $.ajax({
                    url: "/Datasrv/Product/UpdateSubProducts?productId=@Model.Id",
                    type: "POST",
                    data: {subProdList:subProductList},
                    dataType: "json",
                    success: function (data) {
                        //if (data.state == "success") {
                        //    common.msgSuccess("更新成功");
                        //} else {
                        //    common.msgError("更新失败");
                        //}
                    }
                });
            }


        });

        var d = document.createElement('div');
        d.innerHTML = '@Model.Description';
        var descrp = d.innerText || d.textContent
        despObj = $.parseJSON(descrp);
        $("#divDescription").html(initProperties());

        form.render('select');

        editor.customConfig.onchange = function (html) {
            this.editContent = html//动态获取富文本编辑器的内容
            $("#hidEditorContent").text(html);
        }
        //editor.customConfig.uploadImgShowBase64 = true;
        editor.customConfig.uploadImgServer = "/DataSrv/Product/UploadFiles"; //上传URL
        editor.customConfig.uploadFileName = 'imgFile';

        editor.customConfig.uploadImgHooks = {
            before: function (xhr, editor, files) {
                let formdata=new FormData();
                for(let i=0;i<files.length;i++){
                    let url = files[i];
                    //  formdata.append('file[]', url)
                }
            },
            customInsert: function (insertImg, result, editor) {
                for(let i=0;i<result.data.length;i++){
                    let url = result.data[i]
                    // insertImg(url)
                }
            }
        }

        editor.create()
        //initEditor($);
    });

    layui.use(['table', 'common', 'form'], function () {
        var table = layui.table,
            form = layui.form,
            common = layui.common;
        //表格
        table.render({
            id: 'defaultReload'
           , elem: '#subProductTb'
           , height: 'full-440' //高度最大化减去差值
           , url: '/DataSrv/SubProduct/GetAllSubProducts?productId=@Model.Id' //数据接口
           , page: false //开启分页
           , cols: [[ //表头
                     { checkbox: true, fixed: false }
                     , { title: '图片', templet: '<div><img style="width: 90px; height:100px; display: block;" src="{{d.ImageUrl}}"/></div>', width: 120, align: 'center' }
                     , { field: 'Color', title: '颜色', templet: '<div><input type="text" class="layui-input" autocomplete="off" placeholder="请输入售卖价格" value="{{d.Color}}"/></div>', width: 180, align: 'center' }
                     , { field: 'Size', title: '尺码', templet: '<div><input type="text" class="layui-input" autocomplete="off" placeholder="请输入售卖价格" value="{{d.Size}}"/></div>', width: 200, align: 'center' }
                     , { field: 'SkuId', title: 'SKu编号', templet: '<div><input type="text" class="layui-input" autocomplete="off" placeholder="请输入售卖价格" value="{{d.SkuId}}"/></div>', width: 300, align: 'center' }
                     //, { field: 'Price', title: '成本价', templet: '<div><input type="text" class="layui-input" autocomplete="off" placeholder="请输入售卖价格" value="{{d.Price}}"/></div>', width: 180, align: 'center' }
                     , { field: 'UpdateOn', title: '更新时间', templet: '<div>{{showDate(d.UpdateOn)}}</div>', width: 180, align: 'center' }
                     , { field: '', title: '操作', toolbar: "#bar" }
           ]]
        });
        var $ = layui.$, active = {
            reload: function () {
                $('#ajax-loader').fadeOut(); //todo：加载滚动条
                //执行重载
                table.reload('defaultReload', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                });
            }
        };
        //服务器排序
        table.on('sort(defaultruv)', function (obj) {
            //尽管我们的 table 自带排序功能，但并没有请求服务端。
            //有些时候，你可能需要根据当前排序的字段，重新向服务端发送请求，如：
            table.reload('defaultReload', {
                initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。 layui 2.1.1 新增参数
              , where: { //请求参数
                  field: obj.field //排序字段
                , order: obj.type //排序方式
              }
            });
        });

        //监听工具条
        table.on('tool(defaultruv)', function (obj) {
            var data = obj.data;
            if (obj.event === 'detail') {
                common.openTop({
                    detail: true,
                    title: '操作详情', w: '568px', h: '400px', content: '/Datasrv/Product/Detail/' + data.Id, clickOK: function (index) {
                        common.close(index);
                    }
                });
            } else if (obj.event === 'del') {
                layer.confirm('确定要删除吗？', function (index) {
                    $.ajax({
                        url: "/Datasrv/Product/Delete",
                        type: "POST",
                        data: { "Id": data.Id },
                        dataType: "json",
                        success: function (data) {
                            if (data.state == "success") {
                                obj.del();//删除这一行
                                layer.close(index); //关闭弹框
                                common.msgSuccess("删除成功");
                            } else {
                                common.msgError("删除失败");
                            }
                        }
                    });
                });
            } else if (obj.event === 'edit') {
                window.open('/Datasrv/SubProduct/Edit/' + data.Id , "_blank");
                //location.href = '/Datasrv/Product/Edit/' + data.Id;

                //common.openTop({
                //    title: '编辑详情', w: '1600px', h: '780px', content: '/Datasrv/Product/Edit/' + data.Id
                //});
            }
        });
    });

</script>


